import axios from "axios";
import { useAuthStore } from "@/stores/auth";


class Http{
    constructor(){
        this.instance = axios.create({
             baseURL: import.meta.env.VITE_BASE_URL,  
            //baseURL: "http://127.0.0.1:8000", 
            timeout: 6000
        });
        // 发送请求前 添加请求头
        this.instance.interceptors.request.use((config)=>{
            const authStore = useAuthStore()
            const token = authStore.token
            if(token){
                config.headers.Authorization = "JWT "+token
            }
            return config
        })
    }
    post(path,data){
        return new Promise(async (resovle,reject)=>{
            try{
                let result = await this.instance.post(path,data)
                resovle(result.data)
            }catch(err){
                let detail = err.response.data.detail
                console.log("--------------post",detail)
                reject(detail)
            }
        })
    }
    get(path, params){
        return new Promise(async (resolve, reject) => {
            try{
                let result = await this.instance.get(path, {params})
                resolve(result.data)
            }catch(err){
                let detail = err.response.data.detail;
                reject(detail)
            }
        })
    }
    put(path,data){
        return new Promise(async (resovle,reject)=>{
            try{
                let result = await this.instance.put(path,data)
                resovle(result.data)
            }catch(err){
                let detail = err.response.data.detail
                console.log("-----put---------detail",detail)
                reject(detail)
            }
        })
    }
    delete(path){
        return new Promise(async (resovle,reject)=>{
            try{
                let result = await this.instance.delete(path)
                resovle(result)
            }catch(err){
                let detail = err.response.data.detail
                console.log("-----delete---------detail",detail)
                reject(detail)
            }
        }) 

    }
}

export default new Http()